'use strict';

const uidObj = require('uni-id');

const uniConfig = require('uni-config-center');
const uidConfig = uniConfig({
	pluginId: 'uni-id'
}).config();

const {
	Controller
} = require('uni-cloud-router');
const {
	config
} = require('process');

const {
	mainSpaceId
} = require('config-space')

module.exports = class MemberController extends Controller {

	// 注册 
	async register() {
		let response = {
			code: 1,
			msg: '账号注册失败',
			datas: {}
		};
		const {
			sharemid,
			invitation_code,
			name,
			shop_name,
			shop_adress,
			username,
			password,
			code,
			user
		} = this.ctx.data;

		// 验证验证码有效性
		const vcRes = await this.validateSmsCode({
			mobile: username,
			code: code,
			type: "register"
		});
		//  && code !== '123456'
		if (vcRes.data.length !== 1) {
			response.datas = vcRes;
			response.msg = '验证码错误或已失效';
			return response;
		}

		const res = await uidObj.register({
			username,
			password,
			role: ['shop_admin']
		});
		// 配置项
		const config = this.service.utils.getConfig();

		if (res.code == 0) {
			let citys = [user.country, user.province, user.city];
			let nickname = user.nickName;
			if (res.username.length == 11) {
				nickname = `${config.appabbr}-${res.username.substr(7, 4)}`;
			}
			let pMember = await this.db.collection('wmzmall-member').where({
				my_invitation_code: invitation_code
			}).get()
			let member = {
				invitation_code: invitation_code,
				invitation_member_id: pMember.data[0]._id,
				member_name: name || res.username,
				member_password: res.password || '',
				member_mobile: res.username,
				member_access_token: res.token,
				member_nickname: name,
				member_gender: user.gender || 0,
				member_headimg: user.avatarUrl || '',
				member_weixin_headimg: user.avatarUrl || '',
				member_city: citys.filter(x => x).join('-') || '',
			}

			if (vcRes.data && vcRes.data.length) {
				const vcid = vcRes.data[0]._id;
				// 验证码已验证
				await this.db.collection('opendb-verify-codes').doc(vcid).update({
					state: 1
				});
			}
			 
			let app_id = pMember.data[0].app_id
			let shop_id = pMember.data[0].shop_id
			let create_uid = pMember.data[0].create_uid
			member.p_app_id = app_id
			member.p_shop_id = shop_id
			await this.db.collection('uni-id-users').doc(res.uid).update({
				p_app_id: app_id,
				p_shop_id: shop_id
			})
			response.datas.user = res;
			response.datas.member = await this.memberLogin(res, member, sharemid);
		} else {
			response.datas = res;
			response.msg = res.message;
			return response;
		}
		await this.db.collection('wmzmall-register-logs').add({
			name: name,
			shop_name: shop_name,
			shop_adress: shop_adress,
			username: username,
			auth: 0
		})

		response.code = 0;
		response.msg = '注册成功';

		return response;
	}

	// 登录
	async login() {
		let response = {
			code: 1,
			member: {},
			user: {},
			msg: null
		};

		let {
			sharemid,
			username,
			password,
			app_id
		} = this.ctx.data
		try {
			/* let entitlementOrder = await this.db.collection('wmz-entitlement-order').where({
				// app_id: app_id,
				phone: username,
				status: '已付款'
			}).get()
			entitlementOrder = entitlementOrder.data[0]
			if (entitlementOrder) {
				app_id = entitlementOrder.app_id
				username = app_id + "_" + entitlementOrder.ali_user_id
			} */
			const res = await uidObj.login({
				username,
				password,
				needPermission: true
			})
			console.log(res)
			if (!(res && res.uid)) {
				response.msg = '账号不存在或密码错误';
				return response;
			}
			let member = {
				member_access_token: res.token,
				member_password: res.password || '',
				member_mobile: res.username,
			}

			response.code = 0;
			response.member = await this.memberLogin(res, member, sharemid);
			response.user = res;
		} catch (e) {
			response.msg = e.message;
			console.log('catch', e.message);
		}

		return response;
	}

	// 注销
	async logout() {
		const res = await uidObj.logout(this.ctx.event.uniIdToken);
		return res;
	}

	// 验证码
	async sendSmsCode() {
		const {
			mobile,
			invitation_code,
			type
		} = this.ctx.data;

		// 如果验证码类型为 注册，验证手机账号是否已存在
		// 如果验证码类型为 忘记密码，验证手机账号是否存在
		let userRes = {};
		switch (type) {
			case 'register': // 注册
				userRes = await this.db.collection('uni-id-users')
					.where({
						username: mobile,
						role: 'member'
					})
					.field({
						username: true
					})
					.get();
				// console.log('userRes', userRes);
				if (userRes && userRes.data.length === 1) {
					return {
						code: 1,
						msg: '手机号已存在'
					};
				}
				let tDb = uniCloud.database({
					provider: 'tencent',
					spaceId: 'tcb-pfeyfxdttpsw2jy-8cua388a9814'
				})
				const user = await tDb.collection('uni-id-users').where({
					mobile: mobile
				}).get()
				if (user.data.length > 0) {
					return {
						code: 1,
						msg: '账号已在其他平台注册'
					};
				}
				let member = await this.db.collection('wmzmall-member').where({
					my_invitation_code: invitation_code
				}).get()
				if (member && member.data.length === 0) {
					return {
						code: 1,
						msg: '邀请码不存在'
					};
				}
				break;
			case 'forgot-password': // 忘记密码
				userRes = await this.db.collection('uni-id-users')
					.where({
						username: mobile,
						role: 'member'
					})
					.field({
						username: true
					})
					.get();
				// console.log('userRes', userRes);
				if (!(userRes && userRes.data.length === 1)) {
					return {
						code: 1,
						msg: '手机号不存在'
					};
				}
				break;
			default:
				break;
		}

		const res = await uidObj.sendSmsCode({
			...this.ctx.data,
			code: (Math.floor(Math.random() * 1000000) + "").padStart(6, '0') + "",
			templateId: uidConfig['service']['smscode']['templateId']
		});

		return res;
	}

	// 手机号+验证码 登录|注册
	async loginBySms() {
		let response = {
			code: 1,
			member: {},
			user: {},
			msg: null
		};

		const {
			sharemid,
			code, // 验证码
			mobile, // 手机号
			wxcode, // 授权登录 code
			user, // 授权登录用户数据
			type, // 类型  'unbind-bind':微信解绑并绑定
			from = 'mp' // mp小程序 app应用
		} = this.ctx.data;

		// 验证手机号是否有效
		if (!/(^1[0-9][0-9]{9}$)/.test(mobile)) {
			response.msg = '请输入正确的手机号';
			return response;
		}

		const res = await uidObj.loginBySms({
			mobile,
			code,
			role: ['member']
		});

		uniCloud.logger.info('loginBySms1', res);
		response.msg = res.message;

		if (res.code == 0) {
			let member = {};
			// 绑定微信
			let weixin = {};
			if (wxcode && (!res.userInfo.wx_openid ||
					(from == 'mp' && !res.userInfo.wx_openid['mp-weixin']) ||
					(from == 'app' && !res.userInfo.wx_openid['app-plus']))) {

				const wxres = await uidObj.bindWeixin({
					uid: res.uid,
					code: wxcode
				});

				uniCloud.logger.info('wxres', wxres);

				if (wxres.code !== 0) {
					wxres.msg = this.formatCodeMsg(wxres);
					response.code = 100;
					response.datas = wxres;
					response.msg = wxres.msg;
					// await this.db.collection('uni-id-users').doc(res.uid).remove();
					return response;
				}

				if (from == 'app') {
					weixin.app = wxres.openid;
				}
				if (from == 'mp') {
					weixin.mp = wxres.openid;
					weixin.nickname = user.nickname;
				}
				weixin.uuid = wxres.unionid;

				let nickname = user.nickname;
				if (mobile.length == 11) {
					nickname = nickname || `${config.appabbr}-${mobile.substr(7, 4)}`;
				}

				member = {
					member_name: nickname || res.username,
					member_mobile: mobile,
					member_gender: user.gender || 0,
					member_headimg: user.avatar || '',
					member_city: user.comment || '',
					member_weixin: weixin
				}

				await this.db.collection('uni-id-users').doc(res.uid).update({
					nickname: nickname || res.username,
					gender: user.gender || 0,
					mobile_confirmed: 1,
					avatar: user.avatar || '',
				})
			} else {
				const userRes = await this.db.collection('uni-id-users').doc(res.uid).field({
					nickname: true,
					avatar: true
				}).get();

				const [userObj] = userRes.data;
				if (userObj && !userObj.nickname && !userObj.avatar) {
					let nickname = `${config.appabbr}-${mobile.substr(7, 4)}`;
					let headimg =
						'https://vkceyugu.cdn.bspapp.com/VKCEYUGU-7e00db99-ad65-4b9f-a74b-61bccb92b124/74c83ec0-497b-480a-b534-a2906fa1f63a.png';

					member = {
						member_name: nickname,
						member_mobile: mobile,
						member_headimg: headimg,
						member_gender: 0
					}

					await this.db.collection('uni-id-users').doc(res.uid).update({
						nickname: nickname,
						gender: 0,
						mobile_confirmed: 1,
						avatar: headimg
					})
				}
			}

			let memberRes = await this.memberLogin(res, member, sharemid);

			response.code = 0;
			response.member = memberRes;
			response.user = res;
		}

		return response;
	}

	// 微信小程序登录
	async loginByWeixin() {
		let response = {
			code: 1,
			member: {},
			user: {},
			msg: null
		};
		try {
			let {
				app_id,
				shop_id,
				sharemid,
				code,
				user,
				templateId
			} = this.ctx.data;
			if (!app_id) {
				app_id = shop_id
			}
			let openidData = await this.service.wechat.getWechatOpenId(app_id, code, templateId)
			if (openidData.code !== 200) {
				let response = {
					code: 1,
					msg: openidData.msg,
					datas: {}
				};
				return response
			}
			let callFunctionResult = openidData.data
			var params = {
				username: shop_id + "_" + callFunctionResult.openid,
				password: "888888"
			}
			let res = await uidObj.login(params)
			if (res.code !== 0) {
				if (res.code === 10002) {
					params.openid = callFunctionResult.openid
					params.role = ["mall_member"]
					params.app_id = app_id
					params.shop_id = shop_id
					if (user) {
						params.nickname = user.nickname
						params.avatar = user.avatar
						params.gender = user.gender
					}
					res = await uidObj.register(params)
				} else {
					response.msg = res.msg;
					return response;
				}
			}
			// 注册成功，判断是否已绑定手机号
			/* if (res.msg == '注册成功' && !res.mobileConfirmed) {
				response.code = 100;
				response.msg = '请绑定手机号';

				await this.db.collection('uni-id-users').doc(res.uid).remove();
				return response;
			} */

			let member = {
				app_id: app_id,
				shop_id: shop_id,
				member_name: res.userInfo.nickname,
				member_access_token: res.token,
				member_session_key: callFunctionResult.session_key || '',
				member_nickname: res.userInfo.nickname || res.username,
				member_gender: res.userInfo.gender || 0,
				member_headimg: res.userInfo.avatar || '',
				member_weixin_headimg: res.userInfo.avatar || '',
				member_city: res.userInfo.comment || '',
				member_openid: res.openid || ''
			}

			let memberRes = await this.memberLogin(res, member, sharemid);

			if (user) {
				await this.db.collection('uni-id-users').doc(res.uid).update(user);
				const memberUpdObj = {
					member_nickname: user.nickname,
					member_gender: user.gender,
					member_headimg: user.avatar,
					member_weixin_headimg: user.avatar,
					member_city: user.comment
				};
				await this.db.collection('wmzmall-member').doc(res.uid).update(memberUpdObj);

				memberRes = {
					...memberRes,
					...memberUpdObj
				};
			}

			response.code = 0;
			response.member = memberRes;
			response.user = res;
		} catch (e) {
			response.msg = e.message;
			console.log('catch', e.message);
		}

		return response;
	}

	// 微信公众号 code 授权
	async h5WeixinAuth() {
		let response = {
			code: 1,
			datas: {},
			msg: null
		};
		try {
			const {
				code
			} = this.ctx.data;

			// 请求微信公众号获取用户openid接口
			const appid = uidConfig['h5-weixin']['oauth']['weixin']['appid'];
			const appsecret = uidConfig['h5-weixin']['oauth']['weixin']['appsecret'];
			const url =
				`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${appsecret}&code=${code}&grant_type=authorization_code`;

			const res = await this.curl(url, {
				nestedQuerystring: true,
				method: 'get',
				dataType: 'json'
			});

			console.log('h5Weixin oauth res', res.data);
			if (res.data.errcode) {
				response.msg = res.data.errmsg;
				response.code = res.data.errcode;
			} else {
				// 根据用户 openid、access_token 获取用户数据，进行 注册|登录
				// 返回用户数据

				// 根据 openid 查询是否存在数据
				const openid = res.data.openid;

				const uniUserWhere = [];
				uniUserWhere.push({
					wx_openid: {
						'h5-weixin': openid
					}
				});
				if (res.data.unionid) {
					// 存在 unionid
					uniUserWhere.push({
						wx_unionid: res.data.unionid
					});
				}

				const uniUserRes = await this.db.collection('uni-id-users')
					.where(this.db.command.or(uniUserWhere))
					// 不查询敏感数据
					.field({
						password: false,
						password_secret_version: false,
						login_ip_limit: false
					})
					.get();

				console.log('uniUserRes', uniUserRes);
				// 判断是否已注册
				let member = {};
				let [uniUser] = uniUserRes.data;
				if (uniUser == null || !uniUser._id) {
					// 注册 h5Weixin 用户
					uniUser = await this.regH5WeixinUser(res.data);
					console.log('uniUserRes 注册 h5Weixin 用户', uniUser);

					member = {
						member_openid: openid,
						member_nickname: uniUser.nickname,
						member_gender: uniUser.gender,
						member_headimg: uniUser.avatar,
						member_weixin_headimg: uniUser.avatar,
						member_city: uniUser.comment
					};
				} else {
					// 登录获取最新 token 令牌数据
					uniUser.uid = uniUser._id;

					// 校验当前 token 是否已失效
					const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
					if (userRes.code !== 0) {
						// 失效则创建新的 token 并存储
						const tokenRes = await uidObj.createToken({
							uid: uniUser.uid,
							role: uniUser.role
						});

						const tokenList = uniUser.token || [];

						uniUser.token = tokenRes.token;
						uniUser.tokenExpired = tokenRes.tokenExpired;

						tokenList.push(uniUser.token);

						await this.db.collection('uni-id-users')
							.doc(uniUser.uid)
							.update({
								last_login_date: Date.now(),
								last_login_ip: this.ctx.context.CLIENTIP,
								token: tokenList
							});
					} else {
						// 有效则直接返回
						uniUser = userRes;
					}
				}

				// 调用登录公共模块
				let memberRes = await this.memberLogin(uniUser, member, '');

				response.member = memberRes;
				response.user = uniUser;

				response.datas = {
					openid: openid,
					expires_in: res.data.expires_in
				};
				response.code = 0;
			}

		} catch (e) {
			response.msg = e.message;
			console.log('catch', e.message);
		}

		return response;
	}
	// 获取用户基本信息
	async getH5WeixinSnsUserinfo(req) {
		const url =
			`https://api.weixin.qq.com/sns/userinfo?access_token=${req.access_token}&openid=${req.openid}&lang=zh_CN`;

		const res = await this.curl(url, {
			nestedQuerystring: true,
			method: 'get',
			dataType: 'json'
		});

		return res.data;
	}
	// 获取 access_token
	async getH5WeixinAccessToken() {
		let access_token = '';

		// 从数据库获取，判断当前 access_token 是否过期
		// 未过期直接返回数据库中 access_token
		// 过期则从微信服务器获取 access_token 并存储 db

		const appid = uidConfig['h5-weixin']['oauth']['weixin']['appid'];
		const appsecret = uidConfig['h5-weixin']['oauth']['weixin']['appsecret'];

		const url =
			`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${appsecret}`;

		const res = await this.curl(url, {
			nestedQuerystring: true,
			method: 'get',
			dataType: 'json'
		});

		if (res.data.access_token) {
			// 获取 access_token 并存储 db

			access_token = res.data.access_token;
		}

		return access_token;
	}
	// 注册 h5Weixin 公众号用户数据
	async regH5WeixinUser(req) {

		const h5WeixinUserRes = await this.getH5WeixinSnsUserinfo(req);
		// 生成随机密码
		const password = Date.now() + (Math.round(Math.random() * 1000000) + '').padStart(6, '0');
		// 调用 uni-id 注册接口
		const res = await uidObj.register({
			username: req.openid,
			password: password,
			role: ['member'],
			wx_openid: {
				'h5-weixin': h5WeixinUserRes.openid
			},
			wx_unionid: h5WeixinUserRes.unionid,
			avatar: h5WeixinUserRes.headimgurl,
			gender: h5WeixinUserRes.sex,
			nickname: h5WeixinUserRes.nickname
		});

		res.nickname = h5WeixinUserRes.nickname;
		res.gender = h5WeixinUserRes.gender;
		res.avatar = h5WeixinUserRes.headimgurl;
		return res;
	}

	// 支付宝小程序登录
	async loginByAlipay() {
		let response = {
			code: 1,
			member: {},
			user: {},
			msg: null
		};
		try {
			let {
				app_id,
				shop_id,
				sharemid,
				code,
				templateId
			} = this.ctx.data;
			if (!app_id) {
				app_id = shop_id
			}
			let user = {}
			let appletInfoData
			if (templateId) {
				appletInfoData = await this.service.applet.getAppletInfoByTemplateId(templateId)
				app_id = appletInfoData._id
				shop_id = appletInfoData._id
			} else {
				app_id = app_id
				shop_id = app_id
				appletInfoData = await this.service.applet.getAppletInfoById(app_id)
			}
			let openidData = await this.service.alipay.getAlipayOpenId(app_id, code)
			if (openidData.code !== 200) {
				let response = {
					code: 1,
					msg: openidData.msg,
					datas: {}
				};
				return response
			}
			let openid = openidData.data.userId || openidData.data.openId
			if (!openid) {
				response.msg = JSON.stringify(openidData);
				return response;
			}
			let login_appId = app_id
			if (appletInfoData && appletInfoData.m_app_id) {
				app_id = appletInfoData.m_app_id
				shop_id = appletInfoData.m_app_id
			}
			var params = {
				username: shop_id + "_" + openid,
				password: "888888"
			}
			let res = await uidObj.login(params)
			if (res.code !== 0) {
				if (res.code === 10002) {
					params.openid = openid
					params.role = ["mall_member"]
					params.app_id = app_id
					params.shop_id = shop_id
					params.nickname = user.nickname || '未设置'
					params.avatar = user.avatar
					params.gender = user.gender
					params.login_appId = login_appId
					params.login_pay_appId = appletInfoData.alipay.auth_app_id
					res = await uidObj.register(params)
				} else {
					response.msg = res.msg;
					return response;
				}
			}
			// 注册成功，判断是否已绑定手机号
			/* if (res.msg == '注册成功' && !res.mobileConfirmed) {
				response.code = 100;
				response.msg = '请绑定手机号';
		
				await this.db.collection('uni-id-users').doc(res.uid).remove();
				return response;
			} */

			let member = {
				app_id: app_id,
				shop_id: shop_id,
				member_name: res.userInfo.nickname,
				member_access_token: res.token,
				member_nickname: res.userInfo.nickname || '未设置',
				member_gender: res.userInfo.gender || 0,
				member_headimg: res.userInfo.avatar || '',
				member_weixin_headimg: res.userInfo.avatar || '',
				member_city: res.userInfo.comment || '',
				member_openid: res.openid || ''
			}

			let memberRes = await this.memberLogin(res, member, sharemid);

			if (user.nickname) {
				await this.db.collection('uni-id-users').doc(res.uid).update(user);
				const memberUpdObj = {
					member_nickname: user.nickname,
					member_gender: user.gender,
					member_headimg: user.avatar,
					member_weixin_headimg: user.avatar,
					member_city: user.comment
				};
				await this.db.collection('wmzmall-member').doc(res.uid).update(memberUpdObj);

				memberRes = {
					...memberRes,
					...memberUpdObj
				};
			}

			response.code = 0;
			response.member = memberRes;
			response.user = res;
		} catch (e) {
			response.msg = e.message;
			console.log('catch', e.message);
		}

		return response;

		/* let response = {
			code: 1,
			member: {},
			user: {},
			msg: null
		};
		try {
			const {
				sharemid,
				code
			} = this.ctx.data;
			const res = await uidObj.loginByAlipay({
				code,
				role: ['member']
			});

			uniCloud.logger.info(res);

			let member = {
				member_name: res.username || res.userInfo.nickname,
				member_access_token: res.token,
				member_session_key: res.sessionKey || '',
				member_nickname: res.userInfo.nickname || res.username,
				member_gender: res.userInfo.gender || 0,
				member_headimg: res.userInfo.avatar || '',
				member_weixin_headimg: res.userInfo.avatar || '',
				member_city: res.userInfo.comment || '',
				member_openid: res.openid || '',
			}

			response.code = 0;
			response.member = await this.memberLogin(res, member, sharemid);
			response.user = res;

		} catch (e) {
			response.msg = e.message;
			console.log('catch', e.message);
		}

		return response; */
	}

	// 验证验证码有效性
	async validateSmsCode(param) {
		const vcRes = await this.db.collection('opendb-verify-codes').where({
			...param,
			state: 0,
			expired_at: this.db.command.gte(Date.now())
		}).get();

		console.log("vcRes: ", vcRes, param);
		return vcRes;
	}
	// 忘记密码
	async forgotPassword() {
		let response = {
			code: 1,
			msg: '账号不存在'
		};

		const {
			mobile,
			password,
			code
		} = this.ctx.data;

		// 验证验证码有效性
		const vcRes = await this.validateSmsCode({
			mobile: mobile,
			code: code,
			type: "forgot-password"
		});
		if (vcRes.data.length !== 1) {
			response.datas = vcRes;
			response.msg = '验证码错误或已失效';
			return response;
		}

		// 加密密码
		const encryptPwd = await uidObj.encryptPwd(password);
		if (!(encryptPwd && encryptPwd.passwordHash)) {
			response.msg = '密码修改失败';
			return response;
		}

		// 修改密码
		response.datas = await this.db.collection('uni-id-users').where({
			username: mobile
		}).update({
			password: encryptPwd.passwordHash
		});

		if (response.datas.updated === 1) {
			const vcid = vcRes.data[0]._id;
			// 验证码已验证
			await this.db.collection('opendb-verify-codes').doc(vcid).update({
				state: 1
			});

			response.code = 0;
			response.msg = '密码修改成功';
			return response;
		}

		return response;
	}

	// 获取数据
	async data() {
		let response = {
			code: 1,
			member: {},
			stats: {}
		};

		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		const $ = this.db.command.aggregate;
		// 我的订单
		const orderRes = await this.db.collection('wmzmall-order').aggregate()
			.match({
				create_uid: $.eq(uid)
			})
			.group({
				_id: '$state',
				num: $.sum(1)
			})
			.end();

		// 我的足迹
		const browsing = await this.db.collection('wmzmall-goods-history').where({
			create_uid: uid
		}).count();
		// 我的收藏
		const collect = await this.db.collection('wmzmall-member-collect').where({
			create_uid: uid,
			state: '已收藏'
		}).count();
		// todo: 优惠券
		/* let dbCmd = this.db.command
		let entitlementCoupon = await this.db.collection('wmz-entitlement-coupon').where({
			user_id: uid,
			status: "未使用",
			is_query: dbCmd.exists(false)
		}).get()
		entitlementCoupon = entitlementCoupon.data
		if (entitlementCoupon && entitlementCoupon.length > 0) {
			for (var i in entitlementCoupon) {
				let coupon = await this.db.collection('wmzmall-marketing-coupon').doc(entitlementCoupon[i]._id)
					.get()
				if (coupon.data.length === 0) {
					let goods_type = entitlementCoupon[i].goods_type
					let type
					if (goods_type) {
						if (goods_type === 'mobile_coupon') {
							type = 'mobile_recharge'
						} else if (goods_type === 'nfdw_coupon') {
							type = 'nfdw_recharge'
						} else if (goods_type === 'gw_coupon') {
							type = 'gw_recharge'
						} else {
							type = 'mobile_recharge'
						}
					} else {
						type = 'mobile_recharge'
					}
					if (type) {
						let tApp_id = "41d77edc652531e2064b65687de0a691"
						if (entitlementCoupon[i].t_app_id) {
							tApp_id = entitlementCoupon[i].t_app_id
						}
						let goodsData = await this.db.collection('wmzmall-goods').where({
							app_id: tApp_id,
							state: "销售中",
							type: type
						}).get()
						goodsData = goodsData.data
						if (goodsData.length > 0) {
							goodsData = goodsData[0]
							await this.db.collection('wmzmall-marketing-coupon').add({
								name: '话费充值优惠券',
								_id: entitlementCoupon[i]._id,
								is_delete: 0,
								state: '已领取',
								member_id: uid,
								"end_time": 1919687379000,
								"allow_type": "goods",
								"type": "满减",
								"coupon_type": "mobile_coupon",
								price: entitlementCoupon[i].money * 100,
								"allow_jsons": [{
									"_id": goodsData._id
								}]
							})
							await this.db.collection('wmz-entitlement-coupon').doc(entitlementCoupon[i]._id)
								.update({
									is_query: true
								})
						}
					}
				} else {
					await this.db.collection('wmz-entitlement-coupon').doc(entitlementCoupon[i]._id).update({
						is_query: true
					})
				}
			}
		} */
		// 根据当前用户，获取已领取优惠券数据
		const couponRes = await this.db.collection('wmzmall-marketing-coupon')
			.where({
				is_delete: 0,
				state: '已领取',
				member_id: uid
			})
			.get();
		let member_coupon_cnt = couponRes.data.length
		const memberRes = await this.db.collection('wmzmall-member').doc(uid)
			.field({
				member_session_key: false,
				member_password: false
			}).get();
		let memberData = {};
		if (memberRes && memberRes.data.length === 1) {
			memberData = memberRes.data[0];
			if (memberData.member_truename) {
				// 真实姓名脱敏处理
				memberData.member_truename = this.service.utils.desz(memberData.member_truename);
			}
		}
		memberData.member_coupon_cnt = member_coupon_cnt
		if (!memberData.my_invitation_code) {
			memberData.my_invitation_code = new Date().getTime()
			await this.db.collection('wmzmall-member').doc(uid).update({
				my_invitation_code: memberData.my_invitation_code + ""
			})
		}
		response.member = memberData;


		let rankingList = [{
			code: 1,
			name: '智联',
			sum: 10000
		}]
		let messageList = []
		let noticeList = [{
			img: "https://7463-tcb-0ensdli5proairw00b576-0ad17a-1308293149.tcb.qcloud.la/1709052978420_0.png",
			title: '测试通知',
			time: '12-16'
		}]

		const cloudStockRes = await this.db.collection('wmzmall-cloud-stock').aggregate()
			.match({
				create_uid: $.eq(uid)
			})
			.group({
				_id: null,
				num: $.sum('$goods_num')
			})
			.end();
		let cloudNum = 0
		if (cloudStockRes.data[0] && cloudStockRes.data[0].num) {
			cloudNum = cloudStockRes.data[0].num
		}

		const localStockRes = await this.db.collection('wmzmall-local-stock').aggregate()
			.match({
				create_uid: $.eq(uid)
			})
			.group({
				_id: null,
				num: $.sum('$goods_num')
			})
			.end();
		let localNum = 0
		if (localStockRes.data[0] && localStockRes.data[0].num) {
			localNum = localStockRes.data[0].num
		}
		response.stats = {
			order: orderRes.data,
			browsing: browsing.total,
			collect: collect.total,
			local: localNum,
			cloud: cloudNum,
			rankingList: rankingList,
			noticeList: noticeList,
			messageList: messageList
		}
		response.code = 0;

		return response;
	}

	async get_coupon() {

		let response = {
			code: 1,
			datas: []
		};

		let start = new Date().getTime();

		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (user.code == 0) {
				uid = user.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}

		// 请求参数
		const req = this.ctx.data;

		let {
			id
		} = req;

		const couponRes = await this.db.collection('wmzmall-marketing-coupon')
			.doc(id)
			.get();

		response.datas = couponRes;
		let end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;

	}

	async use_coupon() {

		let response = {
			code: 1,
			datas: []
		};

		let start = new Date().getTime();

		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (user.code == 0) {
				uid = user.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}

		// 请求参数
		const req = this.ctx.data;
		let {
			id,
			mobile
		} = req;
		let username = mobile
		let users = await this.db.collection('uni-id-users')
			.where({
				username: username
			})
			.field({
				username: true
			})
			.get();
		let tuid
		if (users.data.length === 0) {
			let password = "888888"
			let res = await uidObj.register({
				username,
				password,
				role: ['member']
			});
			tuid = res.uid
		} else {
			tuid = users.data[0]._id
		}

		let couponRes = await this.db.collection('wmzmall-marketing-coupon')
			.doc(id)
			.get();
		couponRes = couponRes.data[0]
		if (!couponRes.use) {
			await this.db.collection('wmzmall-marketing-coupon').add({
				name: couponRes.name,
				is_delete: couponRes.is_delete,
				state: couponRes.state,
				member_id: tuid,
				"end_time": couponRes.end_time,
				"allow_type": couponRes.allow_type,
				"type": couponRes.type,
				"coupon_type": couponRes.coupon_type,
				price: couponRes.price,
				"allow_jsons": couponRes.allow_jsons,
				mobile: mobile
			})
			await this.db.collection('wmzmall-marketing-coupon')
				.doc(id).update({
					use: true,
					mobile: mobile
				})
		} else {
			if (mobile !== couponRes.mobile) {
				response.msg = '该优惠券已被其他号码使用'
				return response;
			}
		}
		/* const smsRes = await uniCloud.sendSms({
			appid: '__UNI__DA2AF40',
			smsKey: "1d987a96a3dc152c55120e6382f6e7f1",
			smsSecret: "9b3ff3f85da19e9a6302d38c6c1266c4",
			phone: mobile,
			templateId: '31004', // 请替换为自己申请的模板id
			data: {
				url: 'http://catering.wmeizi.com/qwzsDownLoad/index.html'
			}
		})
		console.log(smsRes)	 */

		let end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;

	}

	async receive_coupon() {
		let response = {
			code: 1,
			datas: []
		};

		let start = new Date().getTime();

		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (user.code == 0) {
				uid = user.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}

		// 请求参数
		const req = this.ctx.data;

		let {
			id,
			mobile
		} = req;
		let username = mobile
		let users = await this.db.collection('uni-id-users')
			.where({
				username: username,
				role: 'member'
			})
			.field({
				username: true
			})
			.get();
		let tuid
		if (users.data.length === 0) {
			let password = "888888"
			let res = await uidObj.register({
				username,
				password,
				role: ['member']
			});
			tuid = res.uid
		} else {
			tuid = users.data[0]._id
		}
		let couponRes = await this.db.collection('wmzmall-marketing-coupon')
			.doc(id)
			.get();
		couponRes = couponRes.data[0]
		if (couponRes.receive) {
			response.msg = '该优惠券已被领取了'
			return response;
		}

		await this.db.collection('wmzmall-marketing-coupon').add({
			name: couponRes.name,
			is_delete: couponRes.is_delete,
			state: couponRes.state,
			member_id: uid,
			"end_time": couponRes.end_time,
			"allow_type": couponRes.allow_type,
			"type": couponRes.type,
			"coupon_type": couponRes.coupon_type,
			price: couponRes.price,
			"allow_jsons": couponRes.allow_jsons,
			mobile: mobile
		})
		await this.db.collection('wmzmall-marketing-coupon').add({
			name: couponRes.name,
			is_delete: couponRes.is_delete,
			state: couponRes.state,
			member_id: tuid,
			"end_time": couponRes.end_time,
			"allow_type": couponRes.allow_type,
			"type": couponRes.type,
			"coupon_type": couponRes.coupon_type,
			price: couponRes.price,
			"allow_jsons": couponRes.allow_jsons,
			mobile: mobile
		})
		await this.db.collection('wmzmall-marketing-coupon')
			.doc(id).update({
				receive: true
			})
		let end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;

	}

	// 修改用户指定数据
	async updateUser() {
		let response = {
			code: 1,
			datas: {}
		};

		const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
		response.msg = user.message;
		response.datas = user;

		if (user && user.code == 0) {
			const {
				uniUser,
				useUser
			} = this.getUpdateData(this.ctx.data);

			await this.db.collection('uni-id-users').doc(user.uid).update(uniUser);
			response.datas = await this.db.collection('wmzmall-member').doc(user.uid).update(useUser);
			response.code = 0;
		}

		return response;
	}
	// 获取待修改的数据
	getUpdateData(user) {

		let uniUser = {};
		let useUser = {};
		let mapping = {
			'nickname': 'member_name',
			'truename': 'member_truename',
			'gender': 'member_gender',
			'avatar': 'member_headimg',
			'comment': 'member_city',
			'slogan': 'slogan'
		}

		for (let key in user) {
			if (mapping[key]) {
				uniUser[key] = user[key];
				useUser[mapping[key]] = user[key];
			}
		}

		return {
			uniUser,
			useUser
		};
	}

	// 修改数据
	async update() {
		const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
		if (user && user.code == 0) {
			const {
				nickname,
				gender,
				avatar,
				comment
			} = this.ctx.data;

			await this.db.collection('uni-id-users').doc(user.uid).update({
				nickname,
				gender,
				avatar,
				comment
			});
			await this.db.collection('wmzmall-member').doc(user.uid).update({
				member_nickname: nickname,
				member_gender: gender,
				member_headimg: avatar,
				member_weixin_headimg: avatar,
				member_city: comment
			});
		}

		return user;
	}

	// 收藏
	async collect() {
		const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
		if (user && user.code == 0) {
			const {
				goods_id,
				state
			} = this.ctx.data;

			if (state == '已取消') {
				// 收藏数
				await this.db.collection('wmzmall-goods').where({
					_id: goods_id,
					collect_cnt: this.db.command.gt(0)
				}).update({
					collect_cnt: this.db.command.inc(-1)
				});
			} else {
				// 收藏数
				await this.db.collection('wmzmall-goods').doc(goods_id).update({
					collect_cnt: this.db.command.inc(1)
				});
			}


			let obj_id = user.uid + goods_id;
			return await this.db.collection('wmzmall-member-collect').doc(obj_id).set({
				goods: goods_id,
				state,
				create_uid: user.uid,
				create_time: Date.now()
			});
		}

		return user;
	}

	// 写入会员登录数据
	async memberLogin(res, member, sharemid) {
		// 
		let obj_id = res.uid;
		const nowdate = new Date().getTime();
		const utc8date = this.service.utils.toDateUTC8(Date.now());
		if (res.code == 0) {
			if (res.username && !res.mobile) {
				// 默认开启手机号登录
				await this.db.collection('uni-id-users').doc(res.uid).update({
					mobile: res.username,
					mobile_confirmed: 1
				});
			}
			if (res.mobile && !res.username) {
				// 默认开启手机号+密码登录
				await this.db.collection('uni-id-users').doc(res.uid).update({
					username: res.mobile
				});
			}

			const memberUpdateRes = await this.db.collection('wmzmall-member').doc(obj_id).update({
				...member,
				member_login_cnt: this.db.command.inc(1),
				member_login_current_ip: this.ctx.data.ip || this.ctx.context.CLIENTIP,

				version: this.db.command.inc(1),
				last_modify_uid: res.uid,
				last_modify_time: nowdate
			});

			if (memberUpdateRes && memberUpdateRes.updated <= 0) {
				await this.db.collection('wmzmall-member').doc(obj_id).set({
					...member,
					member_guid: obj_id,
					member_uuid: res.unionid,
					member_coupon_cnt: 0,
					member_amount: 0,
					member_monetary: 0,
					member_login_cnt: 1,
					member_login_first_ip: this.ctx.data.ip || this.ctx.context.CLIENTIP,
					member_login_first_time: nowdate,
					is_plus: '会员',
					bind_has: 0,
					remark: '',
					version: 1,
					state: '已审核',
					yy_mm: this.service.utils.formatdate(utc8date, 'yyyy年MM月'),
					yy_mm_dd: this.service.utils.formatdate(utc8date, 'yyyy年MM月dd日'),
					create_uid: res.uid,
					create_time: nowdate
				});
				// 同步开通笔记功能
				await this.service.utils.openNoteUser(obj_id, {
					uname: member.member_nickname || member.member_name,
					uheadimg: member.member_headimg
				})
			} else {
				// 判断是否已开通笔记功能
				const noteUserRes = await this.db.collection('wmzmall-shopping-user').doc(obj_id).field({
					create_uid: true
				}).get();
				if (noteUserRes.data && !noteUserRes.data.length) {
					// 同步开通笔记功能
					await this.service.utils.openNoteUser(obj_id, {
						uname: member.member_nickname || member.member_name,
						uheadimg: member.member_headimg
					})
				}
			}

			const fxsRes = await this.db.collection('wmzmall-distributor').doc(obj_id).field({
				fxs_uid: true
			}).get();

			if (fxsRes.data && fxsRes.data.length <= 0) {
				// 写入分销商数据
				await this.db.collection('wmzmall-distributor').doc(obj_id).set({
					fxs_uid: obj_id,
					fxs_member_id: obj_id,
					fxs_member_openid: member.member_openid,
					fxs_profit_amount: 0,
					fxs_unprofit_amount: 0,
					fxs_cashout_amount: 0,
					fxs_unsettled_amount: 0,
					fxs_order_cnt: 0,
					fxs_member_cnt: 0,
					fxs_desc: '',
					remark: '',
					state: '启用',
					version: 1,
					is_delete: 0,
					create_time: nowdate,
					create_uid: obj_id,
					create_uname: member.member_name || member.member_nickname
				});

				await this.db.collection('wmzmall-distributor-log').add({
					fxs_uid: obj_id,
					oper_content: '注册|登录默认设为分销商',
					oper_type: '新增',
					oper_ip: this.ctx.data.ip || this.ctx.context.CLIENTIP,
					remark: '',
					version: 1,
					is_delete: 0,
					create_time: nowdate,
					create_uid: obj_id,
					create_uname: member.member_name || member.member_nickname
				});
			}
		}

		// 日志记录
		await this.uidlog(res);

		const memberRes = await this.db.collection('wmzmall-member').doc(res.uid)
			.field({
				member_session_key: false,
				member_password: false
			}).get();
		console.log('memberRes', memberRes);
		let memberData = {};
		if (memberRes && memberRes.data.length === 1) {
			memberData = memberRes.data[0];

			if (!memberData.myfxs_uid && !memberData.bind_has && sharemid && sharemid != obj_id) {
				// 修改登录者的 分销商
				console.log('修改登录者的 分销商', memberData, sharemid);

				// 获得 sharemid 的上级
				let sharemid2 = '';
				let shareData2 = {};

				const shareRes = await this.db.collection('wmzmall-member').doc(sharemid)
					.field({
						myfxs_uid: true
					}).get();
				const [shareUser] = shareRes.data;
				if (shareUser && shareUser.myfxs_uid) {
					// 上上级
					sharemid2 = shareUser.myfxs_uid
				}

				if (sharemid2) {
					shareData2 = {
						myfxs_uid2: sharemid2,
						myfxs_time2: nowdate,
						myfxs_source2: 'member',
						myfxs_order_cnt2: 0,
						myfxs_profit_amount2: 0,
					};
				}

				await this.db.collection('wmzmall-member').doc(obj_id).update({
					myfxs_uid: sharemid,
					myfxs_time: nowdate,
					myfxs_source: 'member',
					myfxs_order_cnt: 0,
					myfxs_profit_amount: 0,

					bind_has: 1,

					...shareData2
				});
				await this.db.collection('wmzmall-distributor').doc(sharemid).update({
					fxs_member_cnt: this.db.command.inc(1)
				});

				// 修改上级
				await this.db.collection('wmzmall-member').doc(sharemid).update({
					bind_has: 1
				});

				if (sharemid2) {
					await this.db.collection('wmzmall-distributor').doc(sharemid2).update({
						fxs_member_cnt: this.db.command.inc(1)
					});

					// 修改上上级
					await this.db.collection('wmzmall-member').doc(sharemid2).update({
						bind_has: 1
					});
				}

				memberData.myfxs_uid = sharemid;
				memberData.myfxs_uid2 = sharemid2;
			}
			// 设置默认我的余额
			if (!memberData.member_amount) memberData.member_amount = 0;

			if (memberData.member_truename) {
				// 真实姓名脱敏处理
				memberData.member_truename = this.service.utils.desz(memberData.member_truename);
			}
		}

		return memberData;
	}

	// 日志记录
	async uidlog(res, type = 'login') {
		let data = {
			deviceId: this.ctx.data.deviceId || this.ctx.context.DEVICEID,
			ip: this.ctx.data.ip || this.ctx.context.CLIENTIP,
			type,
			ua: this.ctx.context.CLIENTUA,
			create_date: Date.now()
		};

		Object.assign(data, res.code === 0 ? {
			user_id: res.uid,
			state: 1
		} : {
			state: 0
		});

		return await this.db.collection('uni-id-log').add(data);
	}

	// 我的优惠券
	async coupon() {

		let response = {
			code: 1,
			datas: []
		};

		let start = new Date().getTime();

		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const user = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (user.code == 0) {
				uid = user.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}

		// 请求参数
		const req = this.ctx.data;

		let {
			page,
			rows,
			state
		} = req;

		const couponRes = await this.db.collection('wmzmall-marketing-coupon')
			.where({
				member_id: uid,
				state: state
			})
			.skip((req.page - 1) * req.rows)
			.limit(req.rows)
			.get();

		response.datas = couponRes;

		let end = new Date().getTime();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;

	}

	// 当前零钱
	async money() {

		let response = {
			code: 1,
			msg: '',
			datas: {}
		};

		const uid = this.ctx.auth.uid;

		const memberRes = await this.db.collection('wmzmall-member').doc(uid)
			.field({
				member_amount: true
			})
			.get();
		let memberData = {};
		if (memberRes && memberRes.data.length === 1) {
			memberData = memberRes.data[0];
		}

		response.datas = memberData;
		response.code = 0;
		return response;
	}

	formatCodeMsg(res) {
		switch (res.code) {
			case 20101:
				return '手机号错误';
			case 20102:
				return '手机号已存在';
			case 30203:
			case 30204:
				return '请重新登录';
			case 60302:
				return '微信号已被绑定，可直接微信授权登录';
			default:
				return res.message || rse.msg;
		}
	}
}